package com.cupk.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.cupk.mapper.StudentMapper;
import com.cupk.mapper.TopicMapper;
import com.cupk.pojo.*;

import com.cupk.mapper.RecordMapper;
import com.cupk.pojo.Record;
import com.cupk.service.RecordService;
import com.cupk.service.StageService;
import com.cupk.service.StudentService;
import com.cupk.service.TopicService;
import com.cupk.service.impl.StageServiceImpl;
import com.cupk.utils.COSUtil;
import com.cupk.utils.ImgUtil;
import com.cupk.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/record")
public class RecordController {
    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    @Autowired
    private RecordService recordService;
    @Autowired
    private StageService stageService;
    @Autowired
    private TopicService topicService;
    @Autowired
    private StudentService studentService;

    @PostMapping("/add")
    public Result addRecord(@RequestBody Map<String, Object> param) {
        List<Map<String, Object>> userAnswer = (List<Map<String, Object>>) param.get("data");
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Boolean status = false;
        for (Map<String, Object> m : userAnswer) {
            Record l = new Record();
            l.setStuId(userId);
            Integer topicId = (Integer) m.get("key");
            l.setTopicId(topicId);

            String answer = (String) m.get("value");
            if (answer == null) {
                return Result.error("禁止不填入内容上传！");
            }
            l.setAnswer(answer);

            l = recordService.dealResult(l);
            if (l.getStatus() == 1) {
                status = true;
            }
            recordService.addRecord(l);
        }
        if (!status) {
            return Result.error("表单未通过系统自动审核，请等待管理员手动审核通过！");
        }
        return Result.success();
    }

    @GetMapping("/preparingList")
    public Result<List<Record>> getPreparingList(@RequestParam Integer stageId) {
        Stage stage = stageService.getStageById(stageId);
        if (stage == null) {
            return Result.error("比赛阶段不存在，无法获取列表!");
        }
        List<Record> rec = recordService.getPreparingList(stageId);
        return Result.success(rec);
    }

    @GetMapping("/finishList")
    public Result<List<Record>> getFinishList(@RequestParam Integer stageId) {
        Stage stage = stageService.getStageById(stageId);
        if (stage == null) {
            return Result.error("比赛阶段不存在，无法获取列表!");
        }
        List<Record> rec = recordService.getFinishList(stageId);
        return Result.success(rec);
    }

    @GetMapping("/detail")
    public Result<List<Record>> getDetail(@RequestParam Integer stageId, @RequestParam Integer stuId) {
        Stage stage = stageService.getStageById(stageId);
        if (stage == null) {
            return Result.error("比赛阶段不存在，无法获取列表！");
        }
        List<Record> rec = recordService.getDetailList(stageId, stuId);
        return Result.success(rec);
    }

    @PostMapping("/acceptRecord")
    public Result acceptRecord(@RequestBody Map<String, Object> param) {
        Integer stageId = (Integer) param.get("stageId");
        Integer stuId = (Integer) param.get("stuId");
        String comment = (String) param.get("comment");
        List<Record> rec = recordService.getDetailList(stageId, stuId);
        if (rec == null) {
            return Result.error("非法的阶段ID和学生ID");
        }
        recordService.acceptRecord(stageId, comment, stuId);
        String accessToken = studentService.getAccessToken(appid, secret);
        String studentId = studentService.findStudentById(stuId).getStuId();  // 根据编号找学号
        String stuOpenId = studentService.findOpenIdByStuId(studentId);
        String stageName = stageService.getStageById(stageId).getName();
        Map<String, Object> teacher = ThreadLocalUtil.get();
        String teacherName = (String) teacher.get("name");
        recordService.PushMessage(accessToken, stuOpenId, stageName, teacherName, 1, comment);
        return Result.success();
    }

    @PostMapping("/acceptRecordBatch")
    public Result acceptRecordBatch(@RequestBody Map<String, Object> param) {
        Integer stageId = (Integer) param.get("stageId");
        List<Integer> stuIdList = (List<Integer>) param.get("stuIdList");
        String comment = (String) param.get("comment");
        for (Integer stuId : stuIdList) {
            List<Record> rec = recordService.getDetailList(stageId, stuId);
            if (rec == null) {
                return Result.error("非法的阶段ID和学生ID组合，学生ID" + String.valueOf(stuId));
            }
            recordService.acceptRecord(stageId, comment, stuId);
        }
        return Result.success();
    }

    @PostMapping("/rejectRecord")
    public Result rejectRecord(@RequestBody Map<String, Object> param) {
        Integer stageId = (Integer) param.get("stageId");
        Integer stuId = (Integer) param.get("stuId");
        String comment = (String) param.get("comment");
        List<Record> rec = recordService.getDetailList(stageId, stuId);
        if (rec == null) {
            return Result.error("非法的阶段ID和学生ID");
        }
        recordService.rejectRecord(stageId, comment, stuId);
        String accessToken = studentService.getAccessToken(appid, secret);
        String studentId = studentService.findStudentById(stuId).getStuId();  // 根据编号找学号
        String stuOpenId = studentService.findOpenIdByStuId(studentId);
        String stageName = stageService.getStageById(stageId).getName();
        Map<String, Object> teacher = ThreadLocalUtil.get();
        String teacherName = (String) teacher.get("name");
        recordService.PushMessage(accessToken, stuOpenId, stageName, teacherName, 0, comment);
        return Result.success();
    }

    @PostMapping("/rejectRecordBatch")
    public Result rejectRecordBatch(@RequestBody Map<String, Object> param) {
        Integer stageId = (Integer) param.get("stageId");
        List<Integer> stuIdList = (List<Integer>) param.get("stuIdList");
        String comment = (String) param.get("comment");
        for (Integer stuId : stuIdList) {
            List<Record> rec = recordService.getDetailList(stageId, stuId);
            if (rec == null) {
                return Result.error("非法的阶段ID和学生ID组合，学生ID" + String.valueOf(stuId));
            }
            recordService.rejectRecord(stageId, comment, stuId);
        }
        return Result.success();
    }

    @GetMapping("/comment")
    public Result getCommentList(@RequestParam Integer stageId) {
        Stage stage = stageService.getStageById(stageId);
        if (stage == null) {
            return Result.error("阶段ID请求非法!");
        }
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Record> ls = recordService.getCommentList(stageId, userId);
        return Result.success(ls);
    }

    @PostMapping("/importPay")
    public Result<String> imp(@RequestParam Integer stageId, @RequestParam Integer money, @RequestParam("file") MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<PayRecord> payList = reader.readAll(PayRecord.class);
        List<Record> rec = recordService.getPreparingList(stageId);
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String strNow = now.format(formatter);
        Integer count = 0;
        for (PayRecord payRecord : payList) {
            if (!money.equals(payRecord.getMoney())) {
                continue;
            }
            String s = payRecord.getTransactionId();
            for (Record r : rec) {
                if (s.equals(r.getResult())) {
                    String res = "账单比对审核通过：" + strNow;
                    recordService.acceptRecordByTransaction(r.getId(), res);
                    count++;
                }
            }
        }
        return Result.success("成功导入了" + String.valueOf(count) + "条记录");
    }

    @GetMapping("/exportAccept")
    public Result exportAccept(@RequestParam Integer stageId) {
        List<Map<String, Object>> res = recordService.getAllInfoByStage(stageId, 1);

        ExcelWriter writer = ExcelUtil.getWriter(true);

        //设置表头
        writer.addHeaderAlias("stu_id_card", "学号");
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("identity_card", "身份证号");
        writer.addHeaderAlias("grade", "年级");
        writer.addHeaderAlias("college", "学院");
        writer.addHeaderAlias("major", "专业");
        writer.addHeaderAlias("classes", "班级");
        writer.addHeaderAlias("phone", "手机号码");

        // 动态添加其他字段的表头
        if (!res.isEmpty()) {
            Map<String, Object> firstRecord = res.get(0);
            for (String key : firstRecord.keySet()) {
                if (!writer.getHeaderAlias().containsKey(key)) {
                    writer.addHeaderAlias(key, key);  // 使用字段名作为表头
                }
            }
        }

        // 写入数据
        writer.write(res);

        // 将数据写入到ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        writer.flush(outputStream, true);
        writer.close();

        // 将ByteArrayOutputStream转换为ByteArrayInputStream
        InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        String download = COSUtil.upLoad(inputStream, ".xlsx", "application/vnd.ms-excel");

        return Result.success(download);
    }

    @GetMapping("/exportReject")
    public Result exportReject(@RequestParam Integer stageId) {
        List<Map<String, Object>> res = recordService.getAllInfoByStage(stageId, 0);

        ExcelWriter writer = ExcelUtil.getWriter(true);

        //设置表头
        writer.addHeaderAlias("stu_id_card", "学号");
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("identity_card", "身份证号");
        writer.addHeaderAlias("grade", "年级");
        writer.addHeaderAlias("college", "学院");
        writer.addHeaderAlias("major", "专业");
        writer.addHeaderAlias("classes", "班级");
        writer.addHeaderAlias("phone", "手机号码");

        // 动态添加其他字段的表头
        if (!res.isEmpty()) {
            Map<String, Object> firstRecord = res.get(0);
            for (String key : firstRecord.keySet()) {
                if (!writer.getHeaderAlias().containsKey(key)) {
                    writer.addHeaderAlias(key, key);  // 使用字段名作为表头
                }
            }
        }

        // 写入数据
        writer.write(res);

        // 将数据写入到ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        writer.flush(outputStream, true);
        writer.close();

        // 将ByteArrayOutputStream转换为ByteArrayInputStream
        InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        String download = COSUtil.upLoad(inputStream, ".xlsx", "application/vnd.ms-excel");

        return Result.success(download);
    }
}
